package com.wyw.hemerocallis.service.impl;

import com.wyw.hemerocallis.account.BalanceInfo;
import com.wyw.hemerocallis.entity.HemerocallisBalance;
import com.wyw.hemerocallis.filter.AccessContext;
import com.wyw.hemerocallis.repository.HemerocallisAddressRepository;
import com.wyw.hemerocallis.repository.HemerocallisBalanceRepository;
import com.wyw.hemerocallis.service.IBalanceService;
import com.wyw.hemerocallis.vo.LoginUserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 余额相关服务接口的实现
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class BalanceServiceImpl implements IBalanceService {

    private final HemerocallisBalanceRepository balanceRepository;

    /**
     * 获取当前登录用户的余额信息
     * @return
     */
    @Override
    public BalanceInfo getCurrentUserBalanceInfo() {
        LoginUserInfo loginUserInfo = AccessContext.getLoginInfo();
        BalanceInfo balanceInfo = new BalanceInfo(loginUserInfo.getId(), 0L);
        HemerocallisBalance hemerocallisBalance = balanceRepository.findByUserId(loginUserInfo.getId());
        if (hemerocallisBalance != null) {
            balanceInfo.setBalance(hemerocallisBalance.getBalance());
        } else {
            //还没有用户的余额记录，这里先创建出来，余额设置为0
            HemerocallisBalance newBalance = new HemerocallisBalance();
            newBalance.setUserId(loginUserInfo.getId());
            newBalance.setBalance(0L);
            log.info("初始化用户的余额信息:{}", balanceRepository.save(newBalance));
        }

        return balanceInfo;
    }

    @Override
    public BalanceInfo deductBalance(BalanceInfo balanceInfo) {
        LoginUserInfo loginUserInfo = AccessContext.getLoginInfo();

        //扣减余额的一个基本原则：扣减额 <= 当前用户额
        HemerocallisBalance hemerocallisBalance =
                balanceRepository.findByUserId(loginUserInfo.getId());

        if(null == hemerocallisBalance || hemerocallisBalance.getBalance() - balanceInfo.getBalance() < 0) {
            throw new RuntimeException("用户余额不足");
        }

        Long sourceBalance = hemerocallisBalance.getBalance();
        hemerocallisBalance.setBalance(hemerocallisBalance.getBalance() - balanceInfo.getBalance());

        log.info("减去余额:{},{},{}", balanceRepository.save(hemerocallisBalance).getId(),
                sourceBalance,
                balanceInfo.getBalance());

        return new BalanceInfo(
                hemerocallisBalance.getUserId(),
                hemerocallisBalance.getBalance()
        );
    }
}
